package com.yc.javaee.tomcat.impl;

import com.yc.javaee.tomcat.Cookie;
import com.yc.javaee.tomcat.HttpServletRequest;
import com.yc.javaee.tomcat.HttpServletResponse;
import com.yc.javaee.tomcat.ServletException;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;

/**
 * 在浏览器端保存少量数据的技术
 * 1. 浏览器可以操作cookie, 并且会在每次发送请求时, 携带cookie数据送到服务器
 * 2. 服务器亦可以操作cookie, 在每次响应时, 可以将cookie推送给浏览器
 */
@WebServlet("/cookie.s")
public class CookieServlet extends HttpServletImpl{
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setStatus(200, "OK");
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                response.getWriter().append(
                        String.format("%s: %s<br>",cookie.getName(), cookie.getValue()));
            }
        } else {
            response.getWriter().append("没有cookie数据!");
        }

        Cookie cookie = new CookieImpl("name", "zhangsan"); // 必须用英文
        cookie.setMaxAge(60 * 60 * 24 * 7);  // 有效期一周
        response.addCookie(cookie);

        cookie = new CookieImpl("a", "not content"); // 必须用英文
        cookie.setMaxAge(0);  // 浏览器立即删除该cookie
        response.addCookie(cookie);
    }
}
